<?php
	# Certifies the existence of user and your password. If exist store user and password and redirect to main page
	# Else shows a message with the error.
	
	# Include DB
	include ("../db/database.php");
	
	# Push data previous informed by user
	$login = $_POST['input_user'];
	$psw = $_POST['input_psw'];
	
	# Error Message (Wrong Login) 
	if(empty($login)){
		header("Location: /itcontrol/com/login/error_login.php");
		exit();
	}
	
	# Error Message (Wrong Password)
	if(empty($psw)){
		header("Location: /itcontrol/com/login/error_psw.php");
		exit();
	}
	
	# Mount fields of Login
	$fieldsL[0] = "name";
	$fieldsL[1] = "lastname";
	$fieldsL[2] = "login";
	
	# Mount fields of Password
	$fieldsP[0] = "psw";
	
	# Mount namefields of Login
	$namefieldsL[0] = "Nome";
	$namefieldsL[1] = "Sobrenome";
	$namefieldsL[2] = "Login";
	
	# Mount namefields of Password
	$namefieldsP[0] = "Login";
	$namefieldsP[1] = "Senha";
	
	# Mount where of Login
	$whereL[0] = "login = '" . $login . "'";
	
	# Mount where of Password
	$whereP[0] = "login = '" . $login . "'";
	$whereP[1] = "psw = '" .$psw . "'";
	
	# Initiate connection with MySql Server
	$dbconnection = new connectDB();		
	
	# Search Login on DB
	$certifiedLogin = mysql_query($dbconnection->selectDB("tb_login", "login", "check", $fieldsL, $namefieldsL, $whereL)) or die("Error: DataBase(login)");
	$verificationLogin = mysql_num_rows($certifiedLogin);
	
	# Array with name and lastname from the logged user
	$array = mysql_fetch_array($certifiedLogin);

	# Initiate the variables
	$name = $array[0];
	$lastname = $array[1];
	
	# Check if the Login and Password exists on DB
	if($verificationLogin == 1){
		$certifiedPsw = mysql_query($dbconnection->selectDB("tb_login", "login", "check", $fieldsP, $namefieldsP, $whereP)) or die("Error: DataBase(login)");
		$verificationPsw = mysql_num_rows($certifiedPsw);
		if ($verificationPsw == 1){
			# Disconnect DB
			$dbconnection->disconnectDB();

			# Create the session with the info from logged user
			session_start();
			
			# Send the info to session (Login, Name, Lastname, Password)
			$_SESSION["login"] = $login;
			$_SESSION["name"] = $name;
			$_SESSION["lastname"] = $lastname;
			$_SESSION["psw"] = $psw;
			
			# Redirect to Main Page
			header("Location: /itcontrol/com/main/main.php");
		}else {
			# Disconnect DB
			$dbconnection->disconnectDB();
			# Error Message (Wrong Password)
			header("Location: /itcontrol/com/login/error_psw.php");
		}
	}else {
		# Disconnect DB
		$dbconnection->disconnectDB();
		# Error Message (Wrong Login)
		header("Location: /itcontrol/com/login/error_login.php");
	}
?>